package com.kobeliu.entity;

public class Demo_35_No557 {

    public static void main(String[] args) {

//        System.out.println(reverseWords("abcd dcba"));
        int[][] nums = new int[5][4];

        System.out.println(nums.length);
        System.out.println(nums[0].length);
        System.out.println(nums[1].length);
        System.out.println(nums[2].length);
        System.out.println(nums[3].length);
        System.out.println(nums[4].length);


    }

    /**
     * O(n) 但是api调用太多 需要改进
     * @param s
     * @return
     */
    public static String reverseWords1(String s) {
        int len = s.length();
        s = s.trim(); //字符串两边防止空格
        StringBuffer sb = new StringBuffer(s);


        int i = 0; //s的指针
        int j = 0; //上一个空格的位置
        String temp = null;
        StringBuffer sb1 = null;

        while(i<len){
            if(s.charAt(i)==' '){
                temp = s.substring(j,i);
                sb1 = new StringBuffer(temp);
                sb.replace(j,i,sb1.reverse().toString());
                j = i+1;
            }
            if(i==len-1){
                //最后一次进来
                temp = s.substring(j,i+1);
                sb1 = new StringBuffer(temp);
                sb.replace(j,i+1,sb1.reverse().toString());
            }
            i++;
        }
        return sb.toString();

    }

    /**
     * 垃圾 还不如上面
     * @param s
     * @return
     */
    public static String reverseWords(String s) {
        s = s.trim(); //字符串两边防止空格
        int len = s.length();
        char[] chars = s.toCharArray();
        String str = null;

        int i = 0; //s的指针
        int j = 0; //上一个空格的位置

        while(i<len){
            if(chars[i]==' '){
                swap(chars,j,i-1);
                j=i+1;
            }
            if(i==len-1){
                //最后一次进来
                swap(chars,j,i);
            }
            i++;
        }

        i=0;
        while(i<len){
            str += chars[i];
            i++;
        }
        return str;

    }

    static void swap(char[] chars,int L,int R){
        char temp = ' ';
        while(L<R){
            temp = chars[L];
            chars[L] = chars[R];
            chars[R] = temp;
            L++;
            R--;
        }


    }
}
